package com.hddf.project.util.http;

import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

import com.hddf.project.util.Stct;

public class JsonHttp {

	/**
	 * 模拟HTTP链接交互数据
	 * 
	 * @param actionName
	 * @return
	 * @throws Exception
	 */
	public static String getDataFromHTTP(String actionName) throws Exception {
		String strResult = "";

		BasicHttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, Stct.HTTP_TIME_OUT);
		HttpConnectionParams.setSoTimeout(httpParams, Stct.HTTP_TIME_OUT);
		HttpClient httpclient = new DefaultHttpClient(httpParams);
		HttpPost httpRequest = new HttpPost(Stct.HTTP_SERVER_ADDRESS + actionName);

		HttpResponse httpResponse = httpclient.execute(httpRequest);
		strResult = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
		httpclient.getConnectionManager().shutdown();
		return strResult;
	}

	/**
	 * 模拟HTTP链接交互数据
	 * 
	 * @param actionName
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String getDataFromHTTP(String actionName, List<NameValuePair> params) throws Exception {
		String strResult = "";

		BasicHttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, Stct.HTTP_TIME_OUT);
		HttpConnectionParams.setSoTimeout(httpParams, Stct.HTTP_TIME_OUT);
		HttpClient httpclient = new DefaultHttpClient(httpParams);
		HttpPost httpRequest = new HttpPost(Stct.HTTP_SERVER_ADDRESS + actionName);
		httpRequest.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

		HttpResponse httpResponse = httpclient.execute(httpRequest);
		strResult = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
		httpclient.getConnectionManager().shutdown();

		return strResult;
	}
}
